import Taro, { Component } from '@tarojs/taro'
import { AtTabs, AtTabsPane } from 'taro-ui'
import { View, ScrollView } from '@tarojs/components'
import { DNavBar, DCarorder, DModal, DItemError, DPaymodel } from '@/components'
import './shoporders.scss'
import http from '@/api'
const getUrlScheme = http.getUrlScheme
export default class Shoporders extends Component {

  constructor(props) {
    super(props)
    this.state = {
      active: 0,
      isShow: false,
      ispayShow: false,
      scrollStyle: window.screen.availHeight,
      footerStatus: false,
      isOpened: false,
      obj1: {
        page: 1,
        limit: 10,
        orStage: 1
      },
      item: {},
      indList: {},
      totalPage: 1,
      list: [],
      creatorId: ""
    }
  }

  componentWillMount() {
    let { active = 0 } = this.$router.params
    if (window.localStorage.getItem('ISPAY')) {
      // this.state.isOpened： = true
      this.setState({
        isOpened: true
      }, () => window.localStorage.removeItem('ISPAY'))
    }
    this.setState({
      active: +active
    })
    this.getSaleOrder(+active)
  }

  componentDidShow() {
    let { obj1, active } = this.state
    if (+active === 0) {
      obj1.page = 1
      obj1.orStage = 1
    } else if (+active === 1) {
      obj1.page = 1
      obj1.orStage = 2
    } else if (+active === 2) {
      obj1.page = 1
      obj1.orStage = 3
    } else if (+active === 3) {
      obj1.page = 1
      obj1.orStage = 4
    }
    this.setState({
      obj1,
      list: [],
      footerStatus: false
    }, () => {
      this.getSaleOrder()
    })
  }


  getSaleOrder(active) {
    let { page, limit, orStage } = this.state.obj1
    let { totalPage } = this.state
    let creatorId = ''
    try {
      if (localStorage.getItem('userInformation')) {
        let { dsfUserEntity } = JSON.parse(localStorage.getItem('userInformation'))
        creatorId = dsfUserEntity.userId
      }
    } catch (err) {

    }

    // creatorId = '1210110786093981905'// '1210110786093981908' //
    let obj = {
      page,
      limit,
      // creatorId: creatorId,//订单买方id
      orStage: active ? +active + 1 : orStage,  //tab状态
      sign: 0 // 标记 买家0，买家1
    }
    if (page > totalPage) {
      return this.setState({
        footerStatus: true
      })
    }

    http.getSaleOrder(obj).then(res => {
      if (res.list && res.list.length > 0) {
        let { list } = this.state
        let _list = []
        if (page > 1) {
          _list = [...list, ...res.list]
        } else {
          _list = [...res.list]
        }

        this.setState({
          list: _list,
          totalPage
        })
      }
    })
  }
  getStatus(status) {
    return {
      $11: `待支付`,
      $21: `待卖家接单`,
      $31: `待卖家上传`,
      $32: `待确认`,
      $33: `待核实`,
      $41: `交易成功`,
      $42: `拒绝接单`,
      $43: `已撤回`,
      $44: `已超时`,
      $45: `交易异常`,
      $49: `待卖家同意退款`
    }[`$${status}`]
  }
  handleClick(value) {
    let { obj1 } = this.state
    this.setState({
      list: [],
      footerStatus: false
    })
    //this.onhandlePay() //测试支付加密 功能开发
    // ,()=>{
    if (value === 0) {
      this.setState({
        obj1: {
          ...obj1,
          page: 1,
          orStage: 1
        }
      }, () => this.getSaleOrder())
    } else
      if (value === 1) {
        this.setState({
          obj1: {
            ...obj1,
            page: 1,
            orStage: 2
          }
        }, () => this.getSaleOrder())
      } else
        if (value === 2) {
          this.setState({
            obj1: {
              ...obj1,
              page: 1,
              orStage: 3
            }
          }, () => this.getSaleOrder())
        } else
          if (value === 3) {
            this.setState({
              obj1: {
                ...obj1,
                page: 1,
                orStage: 4
              }
            }, () => this.getSaleOrder())
          }
    this.setState({
      active: value
    })
    // }
  }
  onScroll = () => {
    this.setState({
      obj1: {
        ...this.state.obj1,
        page: this.state.obj1.page + 1
      }
    }, () => {
      this.getSaleOrder()
    })
  }
  //详情跳转
  handlerprops(item) {
    let { id, orStatus } = item
    Taro.navigateTo({
      url: `/pages/itemdetail/shopdetail?id=${id}&status=${orStatus}`
    })
  }

  onHandleFirst() {
  }
  //确认合同
  onhandleContract(item) {
    http.confirmOrder3(item.id).then(res => {
      if (res === 0) {
        Taro.showToast({
          title: '该合同已确认',
          icon: 'none',
          duration: 800
        })
        setTimeout(() => {
          Taro.redirectTo({
            url: `/pages/shoporders/shoporders?active=2`
          })
        }, 800);
      } else {
        Taro.navigateTo({
          url: `/pages/contractproof/contractproof?id=${item.id}`
        })
      }
    })
  }
  //撤回订单
  onhandleRecall(item) {
    let isShow = !isShow
    this.setState({
      isShow,
      item
    })
  }
  //关闭模态框
  onClose() {
    let isShow = false
    this.setState({
      isShow
    })
  }
  //撤回订单
  onLastHandle() {
    let { item } = this.state
    this.onClose()
    this.drawOrder()
  }

  drawOrder() {
    let { item } = this.state
    http.drawOrder({ orderId: `${item.id}` }).then(res => {
      Taro.navigateTo({
        url: `/pages/itemdetail/shopdetail?id=${item.id}&status=49`
      })
    })
  }
  async onCancelPay(payType = '1') {
    let { indList } = this.state
    if (payType == 8) {
      const url = await getUrlScheme(indList.id, 0)
      window.location.href = url
      return
    }
    http.transCaPayOrder({ id: indList.id, payIp: window.payIp, payType }).then(res => {

      setTimeout(() => {
        // Taro.navigateBack({
        //     delta: 2
        // })
        // Taro.redirectTo({
        //     url: `/pages/consignment/consignment?active=1`
        // })
        //

        if (+payType === 1) {
          window.localStorage.setItem('ISPAY', 1)
        }
        if (!res.payUrl) {
          return Taro.showToast({
            title: '订单状态异常',
            icon: 'none'
          })
        }
        if (payType == 7) {
          let url = encodeURIComponent(res.payUrl)
          return Taro.navigateTo({
            url: `/pages/wxQrCode?payUrl=${url}`
          })
        }
        window.location.href = res.payUrl

      }, 1000)

    })
  }
  handleClose() {
    this.setState({
      ispayShow: false
    })
  }
  //支付订金
  onhandlePay(item) {
    // alert('支付订金')

    this.setState({
      ispayShow: true,
      indList: item || {}
    })
  }
  payFuc(type) {
    let act = 0
    this.setState({
      isOpened: false,
    })
    if (type) {
      act = 1
    }
    Taro.redirectTo({
      url: `/pages/shoporders/shoporders?active=${act}`
    })
  }
  render() {

    const tabList = [{ title: '待支付' }, { title: '待接单' }, { title: '确认合同' }, { title: '已完结' }]
    const {
      active,
      list,
      isShow,
      scrollStyle,
      footerStatus,
    } = this.state
    return (
      <View className='b_shoporders'>
        <DNavBar title={'购车订单'} className='b_shoporders_nav'></DNavBar>
        <View className='b_shoporders__box'>
          <View className='b_shoporders__content'>
            <AtTabs current={active} tabList={tabList} onClick={this.handleClick.bind(this)}>
              <AtTabsPane>
                <ScrollView
                  scrollY
                  scrollWithAnimation
                  lowerThreshold='20'
                  style={`height:${scrollStyle - 100}PX`}
                  onScrollToLower={this.onScroll}>
                  {
                    list && list.map((item, i) => {
                      return <DCarorder
                        key={i}
                        order={item.orNo}
                        status={this.getStatus(item.orStatus)}
                        list={[item.orCarModel]}
                        flag={[item.orCarSourceType, item.orCarEmissionStd, '外观颜色:', item.orCarOutColor]}
                        tipmoney={item.orCarGuiPrice}
                        addre={item.orSaleComp}
                        total={item.orCount}
                        money={item.orTotalPrice}
                        firstText={item.orStatus === '11' && '支付订金'}
                        lastText={item.orStatus !== '11' && '查看订单'}
                        onHandleDetail={this.handlerprops.bind(this, item)}
                        onHandleFirst={this.onhandlePay.bind(this, item)}
                        onHandleLast={this.handlerprops.bind(this, item)}
                      >
                      </DCarorder>
                    })
                  }
                  {
                    footerStatus && <View className='b_shoporders__more'>暂无更多</View>
                  }
                </ScrollView>
              </AtTabsPane>

              <AtTabsPane>
                <ScrollView
                  scrollY
                  scrollWithAnimation
                  lowerThreshold='20'
                  style={`height:${scrollStyle - 50}PX`}
                  onScrollToLower={this.onScroll}>
                  {
                    list && list.map((item, i) => {
                      return <DCarorder
                        key={i}
                        order={item.orNo}
                        status={this.getStatus(item.orStatus)}
                        list={[item.orCarModel]}
                        flag={[item.orCarSourceType, item.orCarEmissionStd, '外观颜色:', item.orCarOutColor]}
                        tipmoney={item.orCarGuiPrice}
                        addre={item.orSaleComp}
                        total={item.orCount}
                        money={item.orTotalPrice}
                        firstText={item.orStatus === '21' && '撤回订单'}
                        lastText={item.orStatus !== '21' && '查看订单'}
                        onHandleDetail={this.handlerprops.bind(this, item)}
                        onHandleFirst={this.onhandleRecall.bind(this, item)}
                        onHandleLast={this.handlerprops.bind(this, item)}
                      >
                      </DCarorder>
                    })
                  }
                  {
                    footerStatus && <View className='b_shoporders__more'>暂无更多</View>
                  }
                </ScrollView>
              </AtTabsPane>

              <AtTabsPane>
                <ScrollView
                  scrollY
                  scrollWithAnimation
                  lowerThreshold='20'
                  style={`height:${scrollStyle - 50}PX`}
                  onScrollToLower={this.onScroll}>
                  {
                    list && list.map((item, i) => {
                      return <DCarorder
                        key={i}
                        order={item.orNo}
                        status={this.getStatus(item.orStatus)}
                        list={[item.orCarModel]}
                        flag={[item.orCarSourceType, item.orCarEmissionStd, '外观颜色:', item.orCarOutColor]}
                        tipmoney={item.orCarGuiPrice}
                        addre={item.orSaleComp}
                        total={item.orCount}
                        money={item.orTotalPrice}
                        firstText={item.orStatus === '32' && '确认合同'}
                        lastText={item.orStatus !== '32' && '查看订单'}
                        onHandleDetail={this.handlerprops.bind(this, item)}
                        onHandleFirst={this.onhandleContract.bind(this, item)}
                        onHandleLast={this.handlerprops.bind(this, item)}
                      >
                      </DCarorder>
                    })
                  }
                  {
                    footerStatus && <View className='b_shoporders__more'>暂无更多</View>
                  }
                </ScrollView>
              </AtTabsPane>
              <AtTabsPane>
                <ScrollView
                  scrollY
                  scrollWithAnimation
                  lowerThreshold='20'
                  style={`height:${scrollStyle - 50}PX`}
                  onScrollToLower={this.onScroll}>
                  {
                    list && list.map((item, i) => {
                      return <DCarorder
                        key={i}
                        order={item.orNo}
                        status={this.getStatus(item.orStatus)}
                        list={[item.orCarModel]}
                        flag={[item.orCarSourceType, item.orCarEmissionStd, '外观颜色:', item.orCarOutColor]}
                        tipmoney={item.orCarGuiPrice}
                        addre={item.orSaleComp}
                        total={item.orCount}
                        money={item.orTotalPrice}
                        firstText='查看订单'
                        onHandleDetail={this.handlerprops.bind(this, item)}
                        onHandleFirst={this.handlerprops.bind(this, item)}
                      >
                      </DCarorder>
                    })
                  }
                  {
                    footerStatus && <View className='b_shoporders__more'>暂无更多</View>
                  }
                </ScrollView>
              </AtTabsPane>
            </AtTabs>
          </View>
          {
            list.length === 0 && <DItemError></DItemError>
          }
        </View>
        <DModal
          isShow={isShow}
          title='撤回订单'
          text='确定要撤回订单吗？'
          firstbtn='取消'
          lastbtn='撤回'
          onFirst={this.onClose.bind(this)}
          onCancel={this.onClose.bind(this)}
          onLast={this.onLastHandle.bind(this)}
        ></DModal>
        <DModal isShow={this.state.isOpened} title="支付提示" text="是否已完成支付？" firstbtn="支付失败" lastbtn="支付完成" onFirst={this.payFuc.bind(this)} onCancel={this.payFuc.bind(this)} onLast={this.payFuc.bind(this, 1)}></DModal>
        <DPaymodel handleClose={this.handleClose.bind(this)} onCancel={this.onCancelPay.bind(this)} isShow={this.state.ispayShow} />
      </View>

    )
  }
}
